package com.bbmc.bttemp.untils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

/**
 * 蓝牙工具类
 *
 * @author baijj
 *
 */
public class BluetoothUtils {
    private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";

    protected static final String TAG = "TAG";

    private BluetoothAdapter ba=null;
    private Set<BluetoothDevice> bluetoothDeviceSet;
    private BluetoothDevice bluetoothDevice;
    boolean flag = true;
    private BluetoothSocket socket; // 蓝牙Socket

    private static BluetoothUtils bu;

    private OutputStream os; // 蓝牙数据输出流

    private InputStream is;

    // 蓝牙单例设计
    public static BluetoothUtils initBluetoothUtils()
            throws BluetoothDisableException, BluetoothNoDeivceException, IOException {
        if (bu == null) {
            bu = new BluetoothUtils(); // 初始化操作
        }
        return bu;
    }

    private BluetoothUtils() throws BluetoothDisableException, BluetoothNoDeivceException, IOException {
        // 获取蓝牙Adapter
        ba = BluetoothAdapter.getDefaultAdapter();

        // 判断蓝牙是否已经连接设备，如果没有连接，则提示
        if (!ba.isEnabled()) {
            throw new BluetoothDisableException();// 蓝牙不可用
        } else {
            // 获取蓝牙列表
            bluetoothDeviceSet = ba.getBondedDevices();
            if (bluetoothDeviceSet != null && bluetoothDeviceSet.size() > 0) {
                bluetoothDevice = bluetoothDeviceSet.iterator().next(); // 拿到第一个蓝牙设备,当前开发版本，支持单个蓝牙设备
                if (bluetoothDevice != null) {
                    socket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
                    socket.connect();
                    os = socket.getOutputStream();
                }
            } else {
                throw new BluetoothNoDeivceException();
            }
        }
    }

    // 蓝牙读和写操作
    public String getBluetoothDeviceName() {
        if (bluetoothDevice != null) {
            return bluetoothDevice.getName();

        }
        return "";
    }

    /**
     * 写一个字符串
     *
     * @param str
     * @throws IOException
     */
    public void writeString(String str) throws IOException {
        if (os != null) {
            os.write(str.getBytes()); // 写出数据，编码格式UTF-8
        }
    }

    public void close() throws IOException {

        flag = false;
        // 关闭流
        if (os != null)
            os.close();
        if (is != null)
            is.close();
        if (socket != null)
            socket.close();

        // 关闭操作
        bu = null; // 对象置空
    }

    // 注册Readable接口
    public void setOnBluetoothReadable(final OnBluetoothReadable obr) throws IOException {
        is = socket.getInputStream();
        new Thread() {
            public void run() {
                while (flag) {
                    String result = "";
                    byte[] buffer = new byte[1024];
                    try {
                        // 接收数据
                        int len = is.read(buffer);

                        result = new String(buffer, 0, len);
                        obr.read(bluetoothDevice, result, is); // 将得到的数据，写出
                        // Log.i(TAG, "读取数据=" + result);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
        }.start();
    }

    // 数据读取接口
    public interface OnBluetoothReadable {
        public abstract void read(BluetoothDevice bluetoothDevice, String result, InputStream is);
    }

    /**
     * 蓝牙不可用异常
     *
     * @author baijj
     *
     */
    public class BluetoothDisableException extends Exception {
    }

    /**
     * 蓝牙无连接设备异常
     *
     * @author baijj
     *
     */
    public class BluetoothNoDeivceException extends Exception {
    }

}
